#include <fhegraphics/App.h>
#include <fhe/prims/Sim.h>
#include <fhe/core/Registerers.h>
#include <fhe/core/Util.h>
#include <QtGui/QApplication>

namespace fhe
{
  namespace graphics
  {
    FHE_NODE( fhegraphics, App );
    FHE_FUNC( fhegraphics, App, run );
    FHE_VAR( fhegraphics, App, fps );
    
    App::App()
      : fps( 100 )
      , lastUpdate_( Sim::time() )
    {
    }
    
    App::~App()
    {
    }
    
    void App::run()
    {
      const char* argv[] = { "fhe" };
      int argc = 1;
      QApplication app( argc, const_cast<char**>( argv ) );
      
      timer_ = new QTimer( &app );
      connect( timer_, SIGNAL( timeout() ), this, SLOT( update() ) );
      timer_->start( 1000. / fps );
      
      app.exec();
    }
    
    void App::update()
    {
      try
      {
        double t = Sim::time();
        double dt = t - lastUpdate_;
        lastUpdate_ = t;
        publish( "update", t, dt );
      }
      catch ( std::exception e )
      {
        FHE_ERROR( "fhe::graphics::App-> caught exception %s", e.what() );
      }
    }
  }
}
